<?php

Yii::import('backend.modules.user.components.*');

/**
 * LoginForm class.
 * LoginForm is the data structure for keeping
 * user login form data. It is used by the 'login' action of 'SiteController'.
 */
class YumLoginForm extends YumFormModel
{
	public $username;
	public $password;
	public $verifyCode;
	public $rememberMe;
	public $email;
	private $_identity;
	

	/**
	 * Declares the validation rules.
	 * The rules state that username and password are required,
	 * and password needs to be authenticated.
	 */
	public function rules()
	{
		return array(
			array('username', 'required', 'message' => Yum::t("Vui lòng nhập tên Tài khoản.")),
			array('password', 'required', 'message' => Yum::t("Vui lòng nhập mật khẩu.")),
			array('verifyCode', 'captcha', 'allowEmpty'=> !CCaptcha::checkRequirements(), 'on' => 'captchaRequired' ),				
			array('verifyCode','required','on'=>'captchaRequired'),			
			array('rememberMe', 'boolean'),
			//array('password', 'authenticate'),
		);
	}
	
	/**
	 * Declares attribute labels.
	 */
	public function attributeLabels()
	{
		return array(
			'username' => 'Tài khoản',
			'password' => 'Mật khẩu',
			'verifyCode' => 'Nhập mã xác nhận',
			'rememberMe' => 'Ghi nhớ tài khoản',
			'email'=>'email'
		);
	}

	/**
	 * Logs in the user using the given username and password in the model.
	 * @return boolean whether login is successful
	 */
	public function login()
	{
		
		$success = $this->loginByUsername();
		if ($success instanceof YumUser) {
			
			$cookie = new CHttpCookie('login_type', serialize('username'));
			$cookie->expire = time() + (10);
			Yii::app()->request->cookies['login_type'] = $cookie;
			
			$user = $success->attributes;
			if(!empty($success->profile->email)){
				$user['email'] = $success->profile->email;
			}
			
			//$data = array('value'=>$user, 'valueDefault'=>serialize('authSSO'), 'name'=>'authSSO');
			//Util::writeCookie($data, Yii::app()->params['authssoCookieTimeout']);
			/*
			if(!empty($_REQUEST['redirect_url'])){
				$session = Util::getSession ();
				$usrID = $success->id;
				$token = $session->get ( 'access_token' );
				if (empty ( $token )) {
					// exprired 15 minute
					$accessToken = Util::encrypt ( time() . Yii::app ()->params ['key'] . md5 ( $usrID ) );
					$token = Util::accessToken ( true, $accessToken );
				}								
			}
			*/
			if(Yum::module()->afterLogin !== false) 
				call_user_func(Yum::module()->afterLogin);
			
			return $success;	
		} else {
			$this->addError('username',Yum::t('Login is not possible with the given credentials'));
		}
		return false;
	}
	
	public function loginOpenId($email)
	{
		$this->email = $email;
		
		$success = $this->loginByUsernameOpenId();
		if ($success instanceof YumUser) {
			$cookie = new CHttpCookie('login_type', serialize('username'));
			$cookie->expire = time() + (3600*24*30);
			Yii::app()->request->cookies['login_type'] = $cookie;
			/** cookie for login SSO **/
			$user = $success->attributes;
			if(!empty($success->profile->attributes['email'])){
				$user['email'] = $success->profile->attributes['email'];
			}
			
			$data = array('value'=>$user, 'valueDefault'=>serialize('authSSO'), 'name'=>'authSSO');
			Util::writeCookie($data, Yii::app()->params['authssoCookieTimeout']);
			/** end **/
			Yum::log(Yum::t(
						'User {username} successfully logged in (Ip: {ip})', array(
							'{ip}' => Yii::app()->request->getUserHostAddress(),
							'{username}' => $success->username)));
			if(!empty($_REQUEST['redirect_url'])){
				$session = Util::getSession ();
				$usrID = $success->id;
				$token = $session->get ( 'access_token' );
				if (empty ( $token )) {
					/* exprired 15 minute */
					$accessToken = Util::encrypt ( time() . Yii::app ()->params ['key'] . md5 ( $usrID ) );
					$token = Util::accessToken ( true, $accessToken );
				}								
			}
			if(Yum::module()->afterLogin !== false) 
				call_user_func(Yum::module()->afterLogin);
			
			return $success;	
		} else {
			$this->addError('username',Yum::t('Login is not possible with the given credentials'));
		}
		return false;
	}
	
	public function loginByUsername() {
		if(Yum::module()->caseSensitiveUsers)
			$user = YumUser::model()->find('username LIKE :username', array(':username' => $this->username));
		else
			$user = YumUser::model()->find('upper(username) LIKE :username', array(':username' => strtoupper($this->username)));
		
		if($user)
			return $this->authenticate($user);
		else 
			$this->addError('username', Yum::t('Tên tài khoản không đúng.'));

		return false;
	}
	
	public function loginByUsernameOpenId() {
		if(Yum::module()->caseSensitiveUsers)
			$user = YumUser::model()->find('username = :username', array(':username' => $this->username));
		else
			$user = YumUser::model()->find('upper(username) = :username', array(':username' => strtoupper($this->username)));
		
		if($user)
			return $this->authenticateOpenId($user);
		else 
			$this->addError('username',Yum::t('Tên tài khoản không đúng.'));

		return false;
	}
	
	public function authenticateOpenId($user)
	{
		$identity = new YumUserIdentity($user->username, $this->password);
		$identity->authenticateLoginOpenId($this->email);
		
		$duration = $this->rememberMe ? 3600*24*30 : 0; // 30 days
		Yii::app()->user->login($identity, $duration);
		Yum::log('User ' . $user->username .' logged in via openid');
		return $user;
	}
	
	public function authenticate($user)
	{
		$identity = new YumUserIdentity($user->username, $this->password);
		$identity->authenticate();
		
		switch($identity->errorCode) {
			case YumUserIdentity::ERROR_NONE:
				$duration = $this->rememberMe ? 3600*24*30 : 0; // 30 days
				Yii::app()->user->login($identity,$duration);
				return $user;
				break;
			case YumUserIdentity::ERROR_USERNAME_INVALID:
				$this->addError("username",Yum::t('Tên tài khoản không đúng.'));
				break;
			case YumUserIdentity::ERROR_EMAIL_INVALID:
				$this->addError("password",Yum::t('Username or Password is incorrect'));
				break;
			case YumUserIdentity::ERROR_STATUS_INACTIVE:
				$this->addError("username",Yum::t('This account is not activated.'));
				break;
			case YumUserIdentity::ERROR_STATUS_BANNED:
				$this->addError("username",Yum::t('This account is blocked.'));
				break;
			case YumUserIdentity::ERROR_STATUS_REMOVED:
				$this->addError('username', Yum::t('Your account has been deleted.'));
				break;

			case YumUserIdentity::ERROR_PASSWORD_INVALID:
				if(!$this->hasErrors())
					$this->addError("username",Yum::t('Tên tài khoản hoặc mật khẩu không đúng.'));
				break;
				return false;
		}
	}
	
}
